﻿#include"XQScrollLabel.h"
#include<QPropertyAnimation>
#include<QLabel>
XQScrollLabel::XQScrollLabel(QWidget* parent)
	:QWidget(parent)
{
	init();
}

XQScrollLabel::XQScrollLabel(const QString& text, QWidget* parent)
	:QWidget(parent)
{
	init();
	m_label->setText(text);
}

XQScrollLabel::~XQScrollLabel()
{
}

QString XQScrollLabel::text() const
{
	return m_label->text();
}

QFont XQScrollLabel::font() const
{
	if(m_label==nullptr)
		return QFont();
	return m_label->font();
}

scrollType XQScrollLabel::textScrollType()const
{
	return m_scrollType;
}

Qt::Alignment XQScrollLabel::alignment() const
{
	return m_label->alignment();
}

QLabel* XQScrollLabel::label() const
{
	return m_label;
}

void XQScrollLabel::setText(const QString& text)
{
	m_label->setText(text);
	adjust();
}

void XQScrollLabel::setFont(const QFont& font)
{
	if (m_label == nullptr)
		return;
	m_label->setFont(font);
	adjust();
}

void XQScrollLabel::setDuration(int time)
{
	m_animation->setDuration(time);
	m_charCount = 0;
	adjust();
}

void XQScrollLabel::setSecondChar(int n)
{
	m_charCount = n;
	adjust();
}

void XQScrollLabel::setScrollType(scrollType type)
{
	m_scrollType = type;
}

void XQScrollLabel::setObjectName(const QString& name)
{
	m_label->setObjectName(name);
}

void XQScrollLabel::setAlignment(Qt::Alignment align)
{
	m_label->setAlignment(align);
}

void XQScrollLabel::init()
{
	init_ui();
}

void XQScrollLabel::init_ui()
{
	m_label = new QLabel(this);
	m_label->setAlignment(Qt::AlignVCenter);
	m_animation = new QPropertyAnimation(this);
	m_animation->setTargetObject(m_label);
	m_animation->setPropertyName("pos");
	//m_animation->setLoopCount(-1); // 使动画无限循环播放
	/*setDuration(8 * 1000);*/
}

void XQScrollLabel::adjust()
{
	if (m_label == nullptr)
		return;
	disconnect(m_animation, &QPropertyAnimation::finished, nullptr,nullptr);
	QFontMetrics metrics(font());
	int width = metrics.horizontalAdvance(text());//字符串总宽度
	m_label->resize(width,height());
	if ((m_scrollType==scrollType::slopOn && width > this->width()) || m_scrollType==scrollType::on)
	{
		
		if (m_charCount != 0)//一秒移动字符数
		{
			m_animation->setDuration(1000* text().size()/ m_charCount);
		}
		m_animation->setStartValue(QPoint(0, 0));
		m_animation->setEndValue(QPoint(-width, 0));
		m_animation->start();
		connect(m_animation, &QPropertyAnimation::finished, [=] {
			if (m_label->pos().x() == -width)
			{
				m_animation->setStartValue(QPoint(this->width(), 0));
				m_animation->setEndValue(QPoint(this->width()- width, 0));
			}
			else
			{
				m_animation->setStartValue(QPoint(0, 0));
				m_animation->setEndValue(QPoint(-width, 0));
			}
		m_animation->start();
			});
	}
	else
	{
		m_animation->stop();
		m_label->move(0, 0);
	}
}

void XQScrollLabel::resizeEvent(QResizeEvent* event)
{
	adjust();
}

void XQScrollLabel::showEvent(QShowEvent* event)
{
}
